<template>
  <div class="lang-edit">
    <Form :model="editData" :rules="ruleValidate" ref="editErrorMessageForm" :label-width="110">
      <!-- 应用名称 -->
      <Form-item prop="appId" :label="$t('module.errCenter.applyName')">
        <Select
          :placeholder="$t('module.extend.tip.applyName')"
          v-model="editData.appId"
          
          :disabled="isEdit"
        >
          <Option v-for="app in appList" :value="app.id" :key="app.id">{{app.appName}}</Option>
        </Select>
      </Form-item>
      <!-- 错误代码 -->
      <Form-item prop="errorCode" :label="$t('module.errCenter.errorCode')">
        <Input
          :placeholder="$t('module.extend.tip.errorCode')"
          :maxlength="64"
          type="text"
          v-model="editData.errorCode"
          :disabled="isEdit"
        />
      </Form-item>
      <!-- 错误类型 -->
      <Form-item prop="errorType" :label="$t('module.errCenter.errorType')">
        <Select
          :placeholder="$t('module.extend.tip.errorType')"
          v-model="editData.errorType"
          
        >
          <Option v-for="type in errorTypes" :value="type.code" :key="type.code">{{type.name}}</Option>
        </Select>
      </Form-item>
      <!-- 错误信息 -->
      <Form-item prop="message" :label="$t('module.errCenter.errorMessage')">
        <LangInput v-model="editData.message" />
      </Form-item>
      <Form-item prop="description" :label="$t('module.errCenter.describe')">
        <Input  type="textarea" :rows="4" :maxlength="1024" v-model="editData.description" />
      </Form-item>
    </Form>
  </div>
</template>

<script>
import locales from "./locales.js";
import { saveErrorData } from "@/api/errorCenterApi";
import { CoreModuleName } from "@/const";
// import LangEdit from "./LangEdit";

const { userInfo } = $store.state[CoreModuleName];
const supportedLanguages = $store.state[CoreModuleName].supportedLanguages;

export default {
  name: "err-edit",
  mixins: [locales],
  // components: { LangEdit },
  data() {
    const vm = this;
    const errorMessageValidater = (rule, value, callback) => {
      let flag = value.filter(item => {
        if (item.value == "") {
          return true;
        }
      });
      if (flag.length > 0 || value.length == 0) {
        callback(new Error(this.$t("module.extend.tip.errorMessage")));
      } else {
        callback();
      }
    };

    let messageInfo = this.messageInfo;
    if (!!messageInfo.errorCodeMessageVOList) {
      messageInfo.errorCodeMessageVOList = JSON.parse(
        JSON.stringify(messageInfo.errorCodeMessageVOList).replace(/errorMessage/g, "value")
      );
    }
    return {
      isEdit: !!messageInfo.id,
      langLabelList: supportedLanguages,
      editData: {
        id: messageInfo.id,
        message: messageInfo.errorCodeMessageVOList || [],
        errorCode: messageInfo.errorCode,
        errorType: !this.messageInfo.id ? "" : messageInfo.errorType.toString(),
        description: messageInfo.description,
        appId: messageInfo.appId
      },

      ruleValidate: {
        appId: [{ required: true, message: this.$t("module.extend.tip.applyName"), trigger: "change" }],
        errorCode: [{ required: true, message: this.$t("module.extend.tip.errorCode"), trigger: "blur" }],
        message: [{ required: true, validator: errorMessageValidater, trigger: "change" }],
        errorType: [{ required: true, message: this.$t("module.extend.tip.errorType"), trigger: "change" }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  props: {
    appList: {
      type: Array,
      default: () => []
    },
    messageInfo: {
      type: Object,
      default: () => ({})
    },
    errorTypes: {
      type: Array,
      default: () => []
    }
  },
  created() {
    this.$emit(
      "SetTitle",
      this.isEdit ? this.$t("module.errCenter.editErrorCode") : this.$t("module.errCenter.createErrorCode")
    );
    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    save() {
      this.$refs["editErrorMessageForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          let errorCodeMessageVOList = JSON.parse(
            JSON.stringify(this.editData.message).replace(/value/g, "errorMessage")
          );
          delete this.editData.message;
          let saveData = { ...this.editData, errorCodeMessageVOList, tenantCode: userInfo.tenantCode };
          saveData.appCode = this.findAppCode(this.editData.appId);
          saveData.appName = this.findAppName(this.editData.appId);
          // console.log(saveData.appCode);
          if (this.messageInfo.id) {
            saveErrorData(saveData)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("common.updateSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          } else {
            saveErrorData(saveData)
              .then(response => {
                this.actions[0].loading = false;
                this.$message.success({
                  content: this.$t("common.createSuccess"),
                  duration: 3
                });
                this.$emit("Close", true);
              })
              .catch(err => {
                this.actions[0].loading = false;
              });
          }
        } else {
          let self = this;
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    },
    // 查找appCode
    findAppCode(appId) {
      for (let appInfo of this.appList) {
        if (appInfo.id === appId) {
          return appInfo.clientId;
        }
      }
    },
    // 查找appNane
    findAppName(appId) {
      for (let appInfo of this.appList) {
        if (appInfo.id === appId) {
          return appInfo.appName;
        }
      }
    }
  }
};
</script>

<style lang="less" scope>
.lang-edit {
  .lang-edit-input input {
    cursor: pointer;
  }
  .global-icon {
    pointer-events: none;
  }
}
</style>
